//! @Author: DengLibin 榆霖
//! @Date:  2022-04-21 09:21:26
//! @Description: 
use actix_web::{
    ResponseError, HttpResponse, body::BoxBody,
    http::{header::ContentType},
};

use derive_more::Display;
use rand::{
    distributions::{Distribution, Standard}, Rng,
};
/// 自定义错误
#[derive(Debug, Display)]
pub enum CustomError {
    #[display(fmt = "Forbidden")]
    Forbidden,

    #[display(fmt = "Unauthorized")]
    Unauthorized,

    #[display(fmt = "InternalServerError")]
    InternalServerError,

    #[display(fmt = "NotFound")]
    NotFound,

    #[display(fmt = "BadRequest")]
    BadRequest,
}

impl Distribution<CustomError> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> CustomError {
        match rng.gen_range(0..4) {
            0 => CustomError::Forbidden,
            1 => CustomError::Unauthorized,
            2 => CustomError::InternalServerError,
            _ => CustomError::BadRequest,
        }
    }
}

/// 实现 ResponseError
impl ResponseError for CustomError {
    fn error_response(&self) -> HttpResponse<BoxBody> {
        match self {
            CustomError::Forbidden => {
                HttpResponse::Forbidden().content_type(ContentType::plaintext()).body("禁止访问")
            }

            CustomError::Unauthorized => {
                HttpResponse::Unauthorized().content_type(ContentType::plaintext()).body("未认证")
            }

            CustomError::InternalServerError => {
                HttpResponse::InternalServerError().content_type(ContentType::plaintext()).body("服务端内部错误")
            }
            CustomError::NotFound => {
                HttpResponse::NotFound().content_type(ContentType::plaintext()).body("资源不存在")
            }

            _ => {
               // HttpResponse::BadRequest().finish()
                HttpResponse::BadRequest().content_type(ContentType::plaintext()).body("错误的请求")
            }
        }
    }
}